<?php

namespace app\controller;

use app\ErrorCode;
use app\exception\ApiException;
use app\Request;
use app\service\JwtService;
use app\service\PasswordMixService;
use app\service\AdminService;

class LoginController
{
    public function  login(Request $request)
    {
        $username = $request->post('username');
        $password = $request->post('password');

        if (!$username || !$password) {
            throw new ApiException("用户名或密码不能为空", ErrorCode::BUSINESS);
        }

        $userInfo = AdminService::getInstance()->getUserInfoByUsername($username);
        $passwordMix = PasswordMixService::getInstance()->mixSalt($password, $userInfo['salt']);
        if ($passwordMix["pass"] != $userInfo['password']) {
            throw new ApiException("密码错误！",ErrorCode::BUSINESS);
        }

        $passwordNewMix = PasswordMixService::getInstance()->mixSalt($password);
        $userInfo->save([
            "password" => $passwordNewMix["pass"],
            "salt" => $passwordNewMix["salt"],
        ]);

        $token = JwtService::getInstance()->encode([
            "id" => $userInfo['id'],
            "username" => $userInfo["username"],
            "type" => $userInfo["type"]
        ]);
        return jsonResponse([
            "token" => $token
        ]);
    }

    public function getLoginUserInfo(Request $request)
    {
        $user = $request->getUserInfo();
        return jsonResponse($user);
    }
}